import { useState, useEffect, useRef } from "react"
import { useNavigate, useParams } from "react-router-dom"
import {
  fetchPostDetailService,
  createCommentService,
  fetchPostLikeService,
  likePostService,
  cancelLikePostService,
  createReportService,
  deleteCommentService,
} from "../api/CommunityApi"
import "./ThreadPage.css"
import defaultAvatar from '../assets/avatar.png';

const status = [
  { id: 1, name: "正常" },
  { id: 2, name: "审核中" },
  { id: 3, name: "已锁定" }
]

const STATUS_MAP = {
  1:{ label: "正常",   className: "status-normal"  },
  2:{ label: "审核中", className: "status-pending" },
  3:{ label: "已锁定", className: "status-locked" },
}

function ThreadPage() {
  const navigate = useNavigate()
  const commentFormRef   = useRef(null);   // 包裹整个表单，用来滚动
  const commentInputRef  = useRef(null);   // 直接聚焦 textarea（可选）
  const { id } = useParams()
  const [postData, setPostData] = useState(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(null)
  const [newComment, setNewComment] = useState("")
  const [replyTo, setReplyTo] = useState(null)
  const [isSubmitting, setIsSubmitting] = useState(false)
  const [isLiked, setIsLiked] = useState(false)
  const [commentImageFile, setCommentImageFile] = useState(null)
  const [commentImagePreview, setCommentImagePreview] = useState(null)

  // 举报相关状态
  const [showReportModal, setShowReportModal] = useState(false)
  const [reportTarget, setReportTarget] = useState(null) // { type: 'post' | 'comment', data: post/comment }
  const [reportReason, setReportReason] = useState("")
  const [isReporting, setIsReporting] = useState(false)

  // 分页状态
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
  })

  const pageSizeOptions = [5, 10, 20, 50]

  const userId = localStorage.getItem("userId")
  const isAdmin = localStorage.getItem("isAdmin") === "true"
  const [deletingCommentId, setDeletingCommentId] = useState(null)
  const [showDeleteCommentModal, setShowDeleteCommentModal] = useState(false)

  const handleCommentImageChange = (e) => {
    const file = e.target.files[0]
    if (file) {
      if (file.size > 500 * 1024) {
        alert("图片大小不能超过500KB")
        return
      }
      setCommentImageFile(file)
      setCommentImagePreview(URL.createObjectURL(file))
    }
  }

  const handleRemoveCommentImage = () => {
    setCommentImageFile(null)
    setCommentImagePreview(null)
  }


  const fetchData = async () => {
    try {
      setLoading(true)
      setError(null)

      const response = await fetchPostDetailService(id, pagination.current, pagination.pageSize)

      if (response.success) {
        // 当page=1时，保存post和author信息
        if (pagination.current === 1) {
          setPostData(response.data)
        } else {
          // 当page>1时，只更新comments数据，保留之前的post和author
          setPostData((prevData) => ({
            ...prevData,
            comments: response.data.comments,
          }))
        }

        // 更新分页信息
        setPagination((prev) => ({
          ...prev,
          total: response.data.post.commentCount || prev.total,
        }))
      } else {
        throw new Error(response.msg || "获取帖子详情失败")
      }

    // 点赞状态单独try
      try {
        const likeResponse = await fetchPostLikeService(id)
        if (likeResponse.success) {
          setIsLiked(likeResponse.data)
        }
      } catch (e) {
        // 点赞状态获取失败不影响主页面显示
        setIsLiked(false)
      }
    } catch (err) {
      setError(err.message)
    } finally {
      setLoading(false)
    }
  }
  useEffect(() => {
    fetchData()
  }, [id, pagination.current, pagination.pageSize])

  const formatDate = (dateString) => {
    const date = new Date(dateString)
    return date.toLocaleString("zh-CN")
  }

  const handleLike = async () => {
    if (isLiked) {
      const response = await cancelLikePostService(id)
      if (!response.success) {
        alert("取消点赞失败，请重试")
        return
      } else {
        fetchData()
        alert("取消点赞成功")
      }
    } else {
      const response = await likePostService(id)
      if (!response.success) {
        alert("点赞失败，请重试")
        return
      } else {
        fetchData()
        alert("点赞成功")
      }
    }
  }

  const handleReply = (comment) => {
    setReplyTo(comment)
    setNewComment(`@${comment.user.username} `)
    // 让浏览器等状态更新完再滚动
    requestAnimationFrame(() => {
      commentFormRef.current?.scrollIntoView({
        behavior: "smooth",
        block: "start",
      })
      // 可选：把光标放进输入框
      commentInputRef.current?.focus()
    })
  }

  const handleSubmitComment = async () => {
    if (!newComment.trim()) return

    setIsSubmitting(true)
    try {
      const formData = new FormData()
      formData.append(
        "commentBO",
        new Blob(
          [JSON.stringify({
            postId: id,
            content: newComment,
            replyToCommentId: replyTo ? replyTo.id : null,
            replyToUserId: replyTo ? replyTo.user.id : null,
          })],
          { type: "application/json" }
        )
      )
      if (commentImageFile) {
        formData.append("file", commentImageFile)
      }
      const response = await createCommentService(formData)

      if (!response.success) {
        throw new Error(response.msg || "评论发布失败")
      }

      // 重置表单
      setNewComment("")
      setReplyTo(null)
      setCommentImageFile(null)
      setCommentImagePreview(null)

      // 重新获取第一页数据（新评论通常在最后）
      setPagination((prev) => ({ ...prev, current: 1 }))

      alert("评论发布成功！")
    } catch (err) {
      alert("评论发布失败，请重试")
    } finally {
      setIsSubmitting(false)
      fetchData()
    }
  }

  const cancelReply = () => {
    setReplyTo(null)
    setNewComment("")
  }

  // 分页处理函数
  const handlePageChange = (page) => {
    // 如果已经有数据，只设置loading为true而不是整个页面
    if (postData) {
      setLoading(true)
    }

    setPagination((prev) => ({ ...prev, current: page }))
    // 滚动到评论区顶部
    document.querySelector(".comments-section")?.scrollIntoView({ behavior: "smooth" })
  }

  const handlePageSizeChange = (size) => {
    setPagination((prev) => ({ ...prev, pageSize: size, current: 1 }))
  }

  // 举报相关函数
  const handleReportPost = () => {
    setReportTarget({
      type: "post",
      data: { ...postData.post, author: postData.author },
    })
    setReportReason("")
    setShowReportModal(true)
  }

  const handleReportComment = (comment) => {
    setReportTarget({
      type: "comment",
      data: comment,
    })
    setReportReason("")
    setShowReportModal(true)
  }

  const handleCloseReportModal = () => {
    setShowReportModal(false)
    setReportTarget(null)
    setReportReason("")
  }

  const handleSubmitReport = async () => {
    if (!reportReason.trim()) {
      alert("请输入举报原因")
      return
    }

    if (reportReason.trim().length < 5) {
      alert("举报原因至少需要5个字符")
      return
    }

    setIsReporting(true)
    try {
      // 构建举报数据
      const reportData = {
        reason: reportReason.trim(),
      }

      if (reportTarget.type === "post") {
        reportData.reportedId = reportTarget.data.id
        reportData.reportedType = "post"
      } else {
        reportData.reportedId = reportTarget.data.id
        reportData.reportedType = "comment"
      }

      const response = await createReportService(reportData)
      if (!response.success) {
        alert("举报提交失败，请重试")
      }
      alert("举报提交成功，管理员会尽快处理")
      handleCloseReportModal()
    } catch (err) {
      alert("举报提交失败，请重试")
    } finally {
      setIsReporting(false)
    }
  }

  const handleUserClick = (userId) => {
    navigate(`/user/${userId}`)
  }

  // 删除评论
  const handleDeleteComment = async () => {
    if (!deletingCommentId) return
    try {
      await deleteCommentService(deletingCommentId)
      // 删除后刷新评论
      fetchData()
    } catch (err) {
      alert("删除失败，请稍后重试")
    } finally {
      setShowDeleteCommentModal(false)
      setDeletingCommentId(null)
    }
  }

  // 渲染分页组件
  const renderPagination = () => {
    const totalPages = Math.ceil(pagination.total / pagination.pageSize)
    const pages = []

    if (totalPages <= 1) return null

    // 计算显示的页码范围
    let startPage = Math.max(1, pagination.current - 2)
    let endPage = Math.min(totalPages, pagination.current + 2)

    if (endPage - startPage < 4) {
      if (startPage === 1) {
        endPage = Math.min(totalPages, startPage + 4)
      } else {
        startPage = Math.max(1, endPage - 4)
      }
    }

    // 首页
    if (startPage > 1) {
      pages.push(
        <button key="1" className="page-btn" onClick={() => handlePageChange(1)}>
          1
        </button>,
      )
      if (startPage > 2) {
        pages.push(
          <span key="start-ellipsis" className="page-ellipsis">
            ...
          </span>,
        )
      }
    }

    // 中间页码
    for (let i = startPage; i <= endPage; i++) {
      pages.push(
        <button
          key={i}
          className={`page-btn ${pagination.current === i ? "active" : ""}`}
          onClick={() => handlePageChange(i)}
        >
          {i}
        </button>,
      )
    }

    // 末页
    if (endPage < totalPages) {
      if (endPage < totalPages - 1) {
        pages.push(
          <span key="end-ellipsis" className="page-ellipsis">
            ...
          </span>,
        )
      }
      pages.push(
        <button key={totalPages} className="page-btn" onClick={() => handlePageChange(totalPages)}>
          {totalPages}
        </button>,
      )
    }

    return pages
  }

  // 修改初始加载状态判断，确保在首次加载时显示完整的加载状态
  if (loading && !postData) {
    return (
      <div className="post-detail-page">
        <div className="loading-container">
          <div className="loading-spinner"></div>
          <p>加载中...</p>
        </div>
      </div>
    )
  }

  if (error) {
    return (
      <div className="post-detail-page">
        <div className="error-container">
          <div className="error-icon">⚠️</div>
          <h3>加载失败</h3>
          <p>错误: {error}</p>
          <button className="retry-btn" onClick={() => window.location.reload()}>
            重试
          </button>
        </div>
      </div>
    )
  }

  const { post, author, comments } = postData || {}

  return (
    <div className="post-detail-page">
      {/* 返回按钮 */}
      <div className="back-nav">
        <button className="back-btn" onClick={() => navigate("/community")}>
          ← 返回论坛
        </button>
      </div>

      {/* 帖子主体 */}
      <div className="post-main-card">
        <div className="post-header">
          <div className="post-title-section">
            <h1 className="post-title">
              {post && (
                <span className={`post-status ${STATUS_MAP[post.status]?.className || ""}`}
                  title={`帖子状态：${STATUS_MAP[post.status]?.label || "未知"}`}
                >
                  {STATUS_MAP[post.status]?.label || "未知"}
                </span>
              )}
              {post?.isPinned === 1 && <span className="pinned-tag">置顶</span>}
              {post?.title}
            </h1>
            <div className="post-meta">
              <span className="post-stats">
                👁️ {post?.viewCount} 浏览 • 💬 {post?.commentCount} 回复 • 👍 {post?.likeCount} 点赞
              </span>
              <span className="post-time">
                发布于 {formatDate(post?.createdTime)}
                {post?.updatedTime !== post?.createdTime && (
                  <span className="updated-time"> • 更新于 {formatDate(post?.updatedTime)}</span>
                )}
              </span>
            </div>
          </div>
        </div>

        <div className="post-body">
          <div className="author-info">
            <div
              className="author-avatar clickable"
              onClick={() => handleUserClick(author?.id)}
              title={`查看 ${author?.username} 的主页`}
            >
              <img src={author?.avatarUrl || defaultAvatar} alt={author?.username} />
            </div>
            <div className="author-details">
              <div
                className="author-name clickable"
                onClick={() => handleUserClick(author?.id)}
                title={`查看 ${author?.username} 的主页`}
              >
                {author?.username}
              </div>
              <div className="author-level">{author?.level}</div>
            </div>
          </div>

          <div className="post-content">
            <div className="content-text">{post?.content}</div>
            {post?.imageUML && (
              <div className="content-image">
                <img src={post?.imageUML || "/placeholder.svg"} alt="帖子图片" />
              </div>
            )}
          </div>

          {post?.status === 1 && (
            <div className="post-actions">
              <button className={`action-btn like-btn ${isLiked ? "liked" : ""}`} onClick={handleLike}>
                <span className="action-icon">{isLiked ? "❤️" : "🤍"}</span>
                <span className="action-text">{isLiked ? "取消点赞" : "点赞"}</span>
                <span className="action-count">{post?.likeCount}</span>
              </button>
              <button className="action-btn reply-btn" onClick={() => {
                setNewComment("");
                setReplyTo(null);
                requestAnimationFrame(() => {
                  commentFormRef.current?.scrollIntoView({
                    behavior: "smooth",
                    block: "start",
                  });
                  // 可选：把光标放进输入框
                  commentInputRef.current?.focus();
                })
              }}>
                <span className="action-icon">💬</span>
                <span className="action-text">回复</span>
              </button>
              <button className="action-btn report-btn" onClick={handleReportPost}>
                <span className="action-icon">🚩</span>
                <span className="action-text">举报</span>
              </button>
            </div>
          )}
          
        </div>
      </div>

      {/* 评论区 */}
      <div className="comments-section">
        <div className="comments-header">
          <h2>评论区 ({pagination.total})</h2>
          <div className="comments-pagination-info">
            第 {pagination.current} 页，共 {Math.ceil(pagination.total / pagination.pageSize) || 1} 页
          </div>
        </div>

        {/* 发表评论 */}
        <div className="comment-form-card" ref={commentFormRef}>
          {replyTo && post?.status === 1 && (
            <div className="reply-indicator">
              <span className="reply-text">
                回复 <strong>@{replyTo.user.username}</strong> 的评论：
                <span className="reply-content">"{replyTo.content}"</span>
              </span>
              <button className="cancel-reply" onClick={cancelReply}>
                ✕
              </button>
            </div>
          )}

          {post?.status === 1 && (
            <div className="comment-form">
              <textarea
                className="comment-input"
                placeholder={replyTo ? `回复 @${replyTo.user.username}...` : "写下你的评论..."}
                value={newComment}
                onChange={(e) => setNewComment(e.target.value)}
                rows={4}
                ref={commentInputRef}
              />
              {/* 新增图片上传和预览 */}
              <div className="form-section" style={{ marginTop: 10 }}>
                <label className="form-label" style={{ fontWeight: 500 }}>
                  <span className="label-icon">🖼️</span>
                  添加图片 <span className="optional">(可选，最大500KB)</span>
                </label>
                {!commentImagePreview ? (
                  <div className="upload-area" style={{ marginBottom: 0 }}>
                    <input
                      type="file"
                      accept="image/*"
                      onChange={handleCommentImageChange}
                      className="file-input"
                      id="comment-image-upload"
                    />
                    <label htmlFor="comment-image-upload" className="upload-label" style={{ minHeight: 60 }}>
                      <div className="upload-icon">📷</div>
                      <div className="upload-text">
                        <span className="upload-main">点击上传图片</span>
                        <span className="upload-sub">支持 JPG、PNG、GIF，最大500KB</span>
                      </div>
                    </label>
                  </div>
                ) : (
                  <div className="image-preview">
                    <div className="preview-header">
                      <span className="preview-title">图片预览</span>
                      <button type="button" onClick={handleRemoveCommentImage} className="remove-image-btn">
                        ✕
                      </button>
                    </div>
                    <div className="preview-container">
                      <img src={commentImagePreview} alt="Preview" className="preview-image" />
                    </div>
                  </div>
                )}
              </div>
              <div className="comment-form-actions">
                <div className="char-count">{newComment.length}/500</div>
                <div className="form-buttons">
                  {replyTo && (
                    <button className="cancel-btn" onClick={cancelReply}>
                      取消回复
                    </button>
                  )}
                  <button
                    className={`submit-btn ${isSubmitting ? "loading" : ""}`}
                    onClick={handleSubmitComment}
                    disabled={isSubmitting || !newComment.trim()}
                  >
                    {isSubmitting ? (
                      <>
                        <span className="btn-spinner"></span>
                        发布中...
                      </>
                    ) : (
                      <>
                        <span className="btn-icon">📝</span>
                        发布评论
                      </>
                    )}
                  </button>
                </div>
              </div>
            </div>
          )}
          
        </div>

        {/* 评论列表 */}
        <div className="comments-list">
          {loading && pagination.current !== 1 ? (
            <div className="comments-loading">
              <div className="loading-spinner"></div>
              <p>加载评论中...</p>
            </div>
          ) : comments?.length === 0 ? (
            <div className="no-comments">
              <div className="no-comments-icon">💬</div>
              <p>暂无评论，来发表第一条评论吧！</p>
            </div>
          ) : (
            comments?.map((comment) => (
              <div key={comment.id} className="comment-card">
                <div className="comment-header">
                  <div className="comment-user">
                    <div
                      className="comment-avatar clickable"
                      onClick={() => handleUserClick(comment.user.id)}
                      title={`查看 ${comment.user.username} 的主页`}
                    >
                      <img
                        src={comment.user.avatarUrl || defaultAvatar}
                        alt={comment.user.username}
                      />
                    </div>
                    <div className="comment-user-info">
                      <div
                        className="comment-username clickable"
                        onClick={() => handleUserClick(comment.user.id)}
                        title={`查看 ${comment.user.username} 的主页`}
                      >
                        {comment.user.username}
                      </div>
                      <div className="comment-user-level">{comment.user.level}</div>
                    </div>
                  </div>
                  <div className="comment-meta">
                    <span className="floor-number">#{comment.floorNumber}楼</span>
                    <span className="comment-time">{formatDate(comment.createdTime)}</span>
                  </div>
                </div>

                {comment.replyToUsername && (
                  <div className="reply-reference">
                    <span className="reply-indicator-text">
                      回复 <strong>@{comment.replyToUsername}</strong> #{comment.replyToFloorNumber}楼：
                    </span>
                    <div className="reply-content-preview">"{comment.replYToContent}"</div>
                  </div>
                )}

                <div className="comment-content">
                  {comment.content}
                  {comment.imageUML && (
                    <div className="comment-image">
                      <img src={comment.imageUML || "/placeholder.svg"} alt="评论图片" />
                    </div>
                  )}
                </div>

                {post?.status === 1 && (
                  <div className="comment-actions">
                    <button className="comment-action-btn" onClick={() => handleReply(comment)}>
                      <span className="action-icon">💬</span>
                      回复
                    </button>
                    <button className="comment-action-btn report-btn" onClick={() => handleReportComment(comment)}>
                      <span className="action-icon">🚩</span>
                      举报
                    </button>
                    {(userId === String(author?.id) || userId === String(comment.user.id) || isAdmin) && (
                    <button
                      className="comment-action-btn"
                      onClick={() => {
                        setDeletingCommentId(comment.id)
                        setShowDeleteCommentModal(true)
                      }}
                    >
                      <span className="action-icon">🗑️</span>
                      删除
                    </button>
                  )}
                  </div>
                )}
                
              </div>
            ))
          )}
          {/* 删除评论确认弹窗 */}
          {showDeleteCommentModal && (
            <div className="modal-overlay" onClick={() => setShowDeleteCommentModal(false)}>
              <div className="modal-content" onClick={e => e.stopPropagation()}>
                <div className="modal-header">
                  <h3>确认删除</h3>
                  <button className="modal-close" onClick={() => setShowDeleteCommentModal(false)}>×</button>
                </div>
                <div className="modal-body">
                  <p>确定要删除该评论吗？删除后不可恢复。</p>
                </div>
                <div className="modal-footer">
                  <button className="btn btn-outline" onClick={() => setShowDeleteCommentModal(false)}>
                    取消
                  </button>
                  <button
                    className="btn btn-primary"
                    style={{ background: "#ff6699", border: "none" }}
                    onClick={handleDeleteComment}
                  >
                    确认删除
                  </button>
                </div>
              </div>
            </div>
          )}
        </div>

        {/* 评论分页 */}
        {pagination.total > 0 && (
          <div className="comments-pagination-wrapper">
            <div className="pagination-info">
              <span>每页显示：</span>
              <select
                value={pagination.pageSize}
                onChange={(e) => handlePageSizeChange(Number(e.target.value))}
                className="page-size-select"
              >
                {pageSizeOptions.map((size) => (
                  <option key={size} value={size}>
                    {size} 条
                  </option>
                ))}
              </select>
            </div>

            <div className="pagination">
              <button
                className="page-btn"
                disabled={pagination.current === 1}
                onClick={() => handlePageChange(pagination.current - 1)}
              >
                上一页
              </button>

              {renderPagination()}

              <button
                className="page-btn"
                disabled={pagination.current === Math.ceil(pagination.total / pagination.pageSize)}
                onClick={() => handlePageChange(pagination.current + 1)}
              >
                下一页
              </button>
            </div>

            <div className="pagination-info">
              共 {pagination.total} 条评论，第 {pagination.current} 页 / 共{" "}
              {Math.ceil(pagination.total / pagination.pageSize)} 页
            </div>
          </div>
        )}
      </div>

      {/* 举报弹窗 */}
      {showReportModal && (
        <div className="report-modal-overlay" onClick={handleCloseReportModal}>
          <div className="report-modal-content" onClick={(e) => e.stopPropagation()}>
            <div className="report-modal-header">
              <h3 className="report-modal-title">
                <span className="report-icon">🚩</span>
                举报{reportTarget?.type === "post" ? "帖子" : "评论"}
              </h3>
              <button className="report-modal-close" onClick={handleCloseReportModal}>
                ✕
              </button>
            </div>

            <div className="report-modal-body">
              {/* 举报对象信息 */}
              <div className="report-target-info">
                <h4 className="report-section-title">举报内容</h4>
                <div className="report-target-card">
                  {reportTarget?.type === "post" ? (
                    <>
                      <div className="report-target-meta">
                        <span className="report-target-author">作者：{reportTarget.data.author?.username}</span>
                        <span className="report-target-type">帖子</span>
                      </div>
                      <div className="report-target-content">
                        <div className="report-target-title">{reportTarget.data.title}</div>
                        <div className="report-target-preview">
                          {reportTarget.data.content?.length > 100
                            ? reportTarget.data.content.substring(0, 100) + "..."
                            : reportTarget.data.content}
                        </div>
                      </div>
                    </>
                  ) : (
                    <>
                      <div className="report-target-meta">
                        <span className="report-target-author">作者：{reportTarget.data.user?.username}</span>
                        <span className="report-target-type">评论</span>
                      </div>
                      <div className="report-target-content">
                        <div className="report-target-preview">
                          {reportTarget.data.content?.length > 150
                            ? reportTarget.data.content.substring(0, 150) + "..."
                            : reportTarget.data.content}
                        </div>
                      </div>
                    </>
                  )}
                </div>
              </div>

              {/* 举报原因输入 */}
              <div className="report-reason-section">
                <h4 className="report-section-title">举报原因</h4>
                <div className="report-reason-input-container">
                  <textarea
                    className="report-reason-input"
                    placeholder="请详细说明举报原因，如：垃圾信息、恶意灌水、违法违规、人身攻击、色情内容、虚假信息等..."
                    value={reportReason}
                    onChange={(e) => setReportReason(e.target.value)}
                    rows={4}
                    maxLength={500}
                  />
                  <div className="report-reason-char-count">
                    {reportReason.length}/500
                    {reportReason.length < 5 && reportReason.length > 0 && (
                      <span className="char-count-warning"> (至少5个字符)</span>
                    )}
                  </div>
                </div>

                {/* 常用举报原因提示 */}
                <div className="report-reason-tips">
                  <span className="tips-title">常见举报原因：</span>
                  <div className="tips-tags">
                    {[
                      "垃圾信息",
                      "恶意灌水",
                      "违法违规",
                      "人身攻击",
                      "色情内容",
                      "虚假信息",
                      "侵犯版权",
                      "其他违规",
                    ].map((tip) => (
                      <button key={tip} type="button" className="tip-tag" onClick={() => setReportReason(tip)}>
                        {tip}
                      </button>
                    ))}
                  </div>
                </div>
              </div>
            </div>

            <div className="report-modal-footer">
              <button className="report-cancel-btn" onClick={handleCloseReportModal}>
                取消
              </button>
              <button
                className={`report-submit-btn ${isReporting ? "loading" : ""}`}
                onClick={handleSubmitReport}
                disabled={isReporting || !reportReason.trim() || reportReason.trim().length < 5}
              >
                {isReporting ? (
                  <>
                    <span className="btn-spinner"></span>
                    提交中...
                  </>
                ) : (
                  <>
                    <span className="report-submit-icon">🚩</span>
                    确认举报
                  </>
                )}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default ThreadPage
